package com.starbugs.wehcat.jdbc;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


@Controller
class UserWebController {

  @RequestMapping(value = "/user-center", method = RequestMethod.GET)
  public String student1(){
    return "user";
  }

}



@RestController
@RequestMapping("/users")
public class UsersController {
  private UserRepository userRepository;

  @Autowired
  public UsersController(UserRepository userRepository) {
    this.userRepository = userRepository;
  }

  @GetMapping("/create")
  public String createTable(){
    userRepository.createTable("user1");
    return "创建 table 成功";
  }
  // 直接把表单的参数写在Controller相应的方法的形参中，适用于get方式提交，不适用于post方式提交

  @GetMapping("/addUser")
  @ResponseBody
  public String addUser(
      @RequestParam(value="id",required = true) int id,
      @RequestParam(value="name",required = true) String name,
      @RequestParam(value="age",required = true) int age,
      @RequestParam(value="points",required = true) int points
  ){
     User user = new User(id, name, age, points);
     userRepository.addUser(user);
    return "添加用户成功";
  }

  @PostMapping("/addUser")
  public Object addUser1(User user){
    userRepository.addUser(user);
    Map<String, String> map = new HashMap<>();
    map.put("code", "200");
    map.put("msg", "success");
    return map;
  }

  @GetMapping("/sendPoints")
  @ResponseBody
  public Object sendPoints(
      @RequestParam(value="from",required = true) String from,
      @RequestParam(value="accept",required = true) String accept,
      @RequestParam(value="num",required = true) int num
  ){
    userRepository.transfer(from, accept, num);
    Map<String, String> map = new HashMap<>();
    map.put("code", "200");
    map.put("msg", "success");
    return map;
  }


  @GetMapping("/findUser")
  @ResponseBody
  public User findUser(@RequestParam(value="id",required = true) int id){
    System.out.println(id);
    User user = userRepository.findUserById(id);
    return user;
  }

  @GetMapping("/findUserAll")
  public List<User> findUserAll(){
    return userRepository.findAll();
  }

}
